package com.gj.tourismcommunity.handler;


import com.gj.tourismcommunity.dto.AuthResponse;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;


@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    
    /**
     * 参数验证异常处理
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public AuthResponse handleValidationException(MethodArgumentNotValidException e,
                                                  HttpServletRequest request) {
        BindingResult bindingResult = e.getBindingResult();
        StringBuilder errorMsg = new StringBuilder();
        
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            errorMsg.append(fieldError.getDefaultMessage()).append("; ");
        }
        
        log.warn("参数验证失败: {} - {}", request.getRequestURI(), errorMsg.toString());
        return new AuthResponse(false, errorMsg.toString());
    }
    
    /**
     * 运行时异常处理
     */
    @ExceptionHandler(RuntimeException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public AuthResponse handleRuntimeException(RuntimeException e, 
                                              HttpServletRequest request) {
        log.error("运行时异常: {} - {}", request.getRequestURI(), e.getMessage());
        return new AuthResponse(false, e.getMessage());
    }
    
    /**
     * 通用异常处理
 * 该方法用于处理系统中的所有未捕获的异常，返回统一的错误响应
 *
 * @ExceptionHandler(Exception.class) 声明该方法为全局异常处理器，处理所有Exception类型的异常
 * @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) 设置响应状态码为500，表示服务器内部错误
 *
 * @param e 捕获到的异常对象
 * @param request 当前的HTTP请求对象，用于获取请求URI等信息
 * @return AuthResponse 统一的认证响应对象，包含错误信息
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public AuthResponse handleException(Exception e, HttpServletRequest request) {
    // 记录系统错误日志，包含请求URI和异常信息
        log.error("系统异常: {} - {}", request.getRequestURI(), e.getMessage(), e);
    // 返回统一的错误响应，提示用户系统内部错误
        return new AuthResponse(false, "系统内部错误，请稍后重试");
    }
}